﻿using B.S.BaseData.Domain.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BaseData.Domain.Implements
{
	/// <summary>
	/// 基础仓储数显
	/// </summary>
	public class BaseRepository<T>:IBaseRepository<T> where T:class
	{
		BaseDataDbContext db;

		public BaseRepository(BaseDataDbContext db)
		{
			this.db = db;
		}


		//上下文,用于事务
		public BaseDataDbContext Context { get; }

		//添加
		public async Task<int> InsertAsync(T entity)
		{
			try
			{
				await  db.Set<T>().AddAsync(entity);
				return await db.SaveChangesAsync();
			}
			catch (Exception)
			{

				throw;
			}
		}

		//显示所有数据
		public IQueryable<T> GetAllAsync()
		{
			try
			{
				return db.Set<T>().AsQueryable();
			}
			catch (Exception)
			{

				throw;
			}
		}


		//显示所有数据(带条件)
		public IQueryable<T> GetAllAsync(Expression<Func<T, bool>> predicate)
		{
			try
			{
				return db.Set<T>().Where(predicate).AsQueryable();
			}
			catch (Exception)
			{

				throw;
			}
		}

		//根据编号查询一条数据
		public async Task<T> GetByIdAsync(int id)
		{
			try
			{
				return await db.Set<T>().FindAsync(id);
			}
			catch (Exception)
			{

				throw;
			}
		}

		//根据条件查询一条数据
		 public async Task<T> GetAsync(Expression<Func<T, bool>> predicate)
		{
			try
			{
				return await db.Set<T>().Where(predicate).FirstOrDefaultAsync();
			}
			catch (Exception)
			{

				throw;
			}
		}


		//修改
		public Task<int> UpdateAsync(T entity)
		{
			try
			{
				db.Set<T>().Update(entity);
				return db.SaveChangesAsync();
			}
			catch (Exception)
			{

				throw;
			}
		}




	}
}
